package tools

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"time"
)

var appid = "xie93cijdc"
var secret = "0933e54e76b24731a2d84b6b463ec04c"

func Hmacsha256(message string) string {
	key := []byte(secret)
	h := hmac.New(sha256.New, key)
	h.Write([]byte(message))
	sha := hex.EncodeToString(h.Sum(nil))
	return base64.StdEncoding.EncodeToString([]byte(sha))
}

// 一个简单的接口token
func GetApiToken(uri string, currentTime int64) (string, error) {
	t := time.Now().UTC().Unix() // 时间统计到秒
	if t-currentTime > 300 {     // 5分钟过期
		return "", fmt.Errorf("token已过期")
	}
	s := fmt.Sprintf("appid%s_secret%s_uri%s_time%d", appid, secret, uri, currentTime)
	token := Hmacsha256(s)
	return token, nil
}
